package com.wydstation.power.collection;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StationResult {

    private final int stationId;
    private final Long localDateTime;
    private final Map<Integer, byte[]> map;

    public StationResult(int stationId, Long localDateTime, Map<Integer, byte[]> map) {
        this.stationId = stationId;
        this.map = map;
        this.localDateTime = localDateTime;
    }


    public byte[] toByteArray() {
        if (map == null || map.isEmpty()) {
            return new byte[0];
        }
        int total = 0, start = 0, end = 0;
        Map<Integer, Integer> indexMap = new HashMap<>(map.size());
        for (Map.Entry<Integer, byte[]> entry : map.entrySet()) {
            byte[] value = entry.getValue();
            total += value.length;
            byte[] v = entry.getValue();
            end += v.length;
            indexMap.put(start, end + 4);
            start += v.length;
        }
        //所有数组的长度+电站id四位+时间戳八位+unitId个数2位+unit个数*12（每个unitId都有自己的id,开始位置，结束位置）
        ByteBuffer totalBuffer = ByteBuffer.allocateDirect(total + 14 + (map.size() * 12));
        totalBuffer.putLong(localDateTime);//时间戳八位
        totalBuffer.putInt(this.stationId);//电站id四位
        totalBuffer.putShort((short) map.size());//unitId个数2位
        indexMap.forEach((k, v) -> {
            totalBuffer.putInt(k);
            totalBuffer.putInt(v);
        });
        ////////////////////////////////
        for (Map.Entry<Integer, byte[]> entry : map.entrySet()) {
            totalBuffer.put(entry.getValue());
            totalBuffer.putInt(entry.getKey());
        }
        totalBuffer.flip();
        byte[] bytes = new byte[totalBuffer.position()];
        totalBuffer.get(bytes);
        return bytes;
    }


}

